// pages/customer-service/customer-service.js
const Toast = require('../../utils/toast');
const request = require('../../utils/request');

Page({
  data: {
    config: {
      system_name: '',
      customer_service_name: '',
      customer_service_phone: '',
      customer_service_wechat: '',
      customer_service_email: '',
      customer_service_qq: '',
      customer_service_work_time: ''
    }
  },

  onLoad() {
    this.loadConfig();
  },

  async loadConfig() {
    try {
      // 先尝试从全局配置读取
      const app = getApp();
      const globalConfig = app.globalData.systemConfig;
      if (globalConfig && globalConfig.customer_service_name) {
        this.setData({
          config: globalConfig
        });
        return;
      }

      // 如果全局没有，从接口获取
      const res = await request.get('/config/customer-service/info');
      if (res.success) {
        this.setData({
          config: {
            customer_service_name: res.data.name || '客服小助手',
            customer_service_phone: res.data.phone || '',
            customer_service_wechat: res.data.wechat || '',
            customer_service_email: res.data.email || '',
            customer_service_qq: res.data.qq || '',
            customer_service_work_time: res.data.work_time || '周一至周五 9:00-18:00'
          }
        });
      }
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  },

  // 复制联系方式
  copyContact(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.currentTarget.dataset.value;
    
    if (!value) {
      Toast.error('联系方式未配置');
      return;
    }

    wx.setClipboardData({
      data: value,
      success: () => {
        const typeNames = {
          phone: '电话',
          wechat: '微信号',
          email: '邮箱',
          qq: 'QQ号'
        };
        Toast.success(`已复制${typeNames[type] || '联系方式'}`);
      }
    });
  },

  // 拨打电话
  callPhone() {
    const phone = this.data.config.customer_service_phone;
    if (!phone) {
      Toast.error('电话未配置');
      return;
    }
    wx.makePhoneCall({
      phoneNumber: phone.replace(/[-\s]/g, ''),
      fail: (err) => {
        console.error('拨打失败:', err);
        Toast.error('拨打失败');
      }
    });
  }
});

